// pages/home/home.js
var orderInfo = require("../data/data.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabList:[
      {
        id:0,
        value: '待确认',
        isclick: true
      },
      {
        id:1,
        value: '进行中',
        isclick: false
      },
      {
        id:2,
        value: '已完成',
        isclick: false
      }
    ],
    active:'0',
    orderlist:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.setData({
    //   orderlist:orderInfo.orderlist
    // });
    const token = wx.getStorageSync('token');
    const app = getApp();
    const _this = this;
    const aurl = app.globalData.url;
    if (token == null || token == '') {
      //登陆
      wx.login({
        success (res) {
          if (res.code) {
            // 发起网络请求
            wx.request({
              url:'https://api.weixin.qq.com/sns/jscode2session',
              data: {
                appid: app.globalData.appid,
                secret: app.globalData.secret,
                js_code: res.code,
                grant_type: 'authorization_code'
              },
              success: res => {
                if (res.data.openid) {
                  console.log('成功获取openid:', res.data.openid); 
                  wx.request({
                    url: aurl + "master/v1/queryMaster",
                    method: 'POST',
                    data: {
                      openid: res.data.openid
                    },
                    success: res => {
                       // 后期需要加逻辑处理未注册
                       if(res.data.data == null) {
                          return;
                       }
                        // 成功获取到openid
                        wx.setStorageSync('token', res.data.data.openID);
                        // 根据openid获取用户名称和手机号
                        const app = getApp();
                        // app.globalData.userInfo.name = res.data.data.name;
                        // app.globalData.userInfo.phone = res.data.data.phone;
                        const photoUrl = res.data.data.photo  != null ? res.data.data.photo  : "/icons/img1.svg";
                      //debugger
                        _this.setData({
                          personal: {
                            name: res.data.data.name,
                            phone: res.data.data.phone,
                            photo:photoUrl != "null" ? photoUrl : "/icons/img1.svg",
                            varify: true
                          }
                        });
                        // debugger
                        _this.getData(res.data.data.openID)
                    },
                    fail: res => {
                    }
                  })
                } else {
                  console.error('获取openid失败:', res.data.errmsg); // 没有获取到openid，返回错误信息
                }
              },
              fail: err => {
                console.error('请求失败:', err.errMsg); // 请求失败，返回错误信息
              }
            })
          } else {
              console.log('登录失败！' + res.errMsg)
          }
        }
      })
    } else {
      const token = wx.getStorageSync('token');
      this.getData(token)
    }

  },

  getData(token) {
    const app = getApp()
    wx.request({
      url: app.globalData.url + 'form/v1/querMasterForm/Dealing',
      method: "POST",
      data: {
        openid: token
      },
      success: res => {
        this.setData({
          orderlist:res.data.data,
        });
        const active = this.data.active
        if (this.data.active == 0) {
          this.sortList();
        } else {
          this.sortListNew();
        }
      },
      fail: res => {

      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    this.onLoad()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 切换tab
  changeTab(e){
    var _this = this;
    this.setData({
      active: e.currentTarget.dataset.index
    })
    var index = e.currentTarget.dataset.index;
    var origin = this.data.tabList

    for(let i = 0; i < origin.length; i++){
      origin[i].isclick = false;
      origin[index].isclick = true;
    }
    _this.setData({
      tabList:origin
    })
    const token = wx.getStorageSync('token')
    this.getData(token)
  },
  click: function(e){
    let data = JSON.stringify(e.currentTarget.dataset.order);
    wx.navigateTo({
      url: '/pages/home/details/details?order=' + data,
    })
  },
  clickButton: function(e){
    //确认订单信息
    const order = e.currentTarget.dataset.order.orderID;
    console.log(order);
    const app = getApp()
    const url = app.globalData.url
    wx.request({
      url: url + "form/v1/updateByMaster/Form",
      method: 'POST',
      data: {
        orderID:order,
        status: 2,
      },
      success: res => {
        wx.showToast({
          title: '确认成功',
          icon: 'success',
          mask: 50
        })
        this.onLoad()
      }

    })
  },
  sortList: function(){
    var list = this.data.orderlist;
    // debugger
    for(var i=0; i<list.length; i++){
      var time = list[i].ordertime
      var date = list[i].orderdate
    }
    list.sort(this.comparehour(time));
    list.sort(this.comparedate(date));
    this.setData({
      orderlist: list
    });
  },
  comparedate: function(property) {
    // console.log(property); 
    return function (a, b) { 
      var value1 = Date.parse(new Date(a.orderdate));  //转换成十六进制获取日期
      var value2 = Date.parse(new Date(b.orderdate));
      // console.log(value1-value2);
      return value1-value2; //value1-value2是从小到大排序 反过来则是从大到小的排序
    }
  },
  comparehour: function(property) {
    // console.log(property);
    return function (a, b) {
      // var value1 = a.time.slice(0,2)  //slice(0,2) 获取字符串前两位进行比较
      // var value2 = b.time.slice(0,2)
      var value1 = a.ordertime.slice(0,2)  //slice(0,2) 获取字符串前两位进行比较
      var value2 = b.ordertime.slice(0,2)
      // console.log(value1-value2)
      return value1 - value2 //value1-value2是从小到大排序 反过来则是从大到小的排序
    }
  },
  //降序排
  comparedateNew: function(property) {
    // console.log(property); 
    return function (a, b) { 
      var value1 = Date.parse(new Date(a.orderdate));  //转换成十六进制获取日期
      var value2 = Date.parse(new Date(b.orderdate));
      // console.log(value1-value2);
      return value2-value1; //value1-value2是从小到大排序 反过来则是从大到小的排序
    }
  },

  comparehourNew: function(property) {
    // console.log(property);
    return function (a, b) {
      var value1 = a.ordertime.slice(0,2)  //slice(0,2) 获取字符串前两位进行比较
      var value2 = b.ordertime.slice(0,2)
      // console.log(value1-value2)
      return value2 - value1 //value1-value2是从小到大排序 反过来则是从大到小的排序
  
    }
  },
  
  sortListNew: function(){
    var list = this.data.orderlist;
    for(var i=0; i<list.length; i++){
      var time = list[i].ordertime
      var date = list[i].orderdate
    }
    list.sort(this.comparehourNew(time));
    list.sort(this.comparedateNew(date));
    this.setData({
      orderlist: list
    });
  }
})